/*******************************************************************
  File Name      : WF5803
  Description       :
  Created on: 2019-1-14
  Author: Admin
********************************************************************/
#include "WF5803.h"

u8 RawData[5] = {0};
long reading = 0;
float fDat = 0;
float Press_Data = 0;
float Temp_Data = 0;
void WF5803_I2C_ReadNByte(u8 DeviceAddr, u8 RegAddr, u8 *pBuf, u8 num);
void WF5803_I2C_WriteCMD(u8 DeviceAddr, u8 RegAddr, u8 CMD);
/********************************************************************
  Function Name   : WF5803_I2C_WriteCMD.
  Description       : None.
  Input             : None.
  Output            : None.
  Return            : None.
********************************************************************/
void WF5803_I2C_WriteCMD(u8 DeviceAddr, u8 RegAddr, u8 CMD)
{
  IIC_Start();
  IIC_Send_Byte(DeviceAddr & 0XFE);   //写器件地址
  IIC_Wait_Ack();
  IIC_Send_Byte(RegAddr);      //写寄存器地址
  IIC_Wait_Ack();
  IIC_Send_Byte(CMD);      //写命令数据
  IIC_Wait_Ack();
  IIC_Stop();
}
/********************************************************************
  Function Name   : WF5803_I2C_ReadNByte.
  Description       : 连续读数据
  Input             : None.
  Output            : None.
  Return            : None.
********************************************************************/
void WF5803_I2C_ReadNByte(u8 DeviceAddr, u8 RegAddr, u8 *pBuf, u8 num)
{
  u8 r_ReadData = 0;
  u8 n = 0;

  IIC_Start();
  IIC_Send_Byte(DeviceAddr & 0XFE);   //写器件地址
  IIC_Wait_Ack();
  IIC_Send_Byte(RegAddr);             //写寄存器地址
  IIC_Wait_Ack();
  IIC_Start();
  IIC_Send_Byte(DeviceAddr | 0X01);   //写器件地址与读
  IIC_Wait_Ack();
  for (n = 0; n < num; n++)
  {
    pBuf[n] = IIC_Read_Byte();      //读数据
    IIC_Ack();
  }

  IIC_Stop();
}

/********************************************************************
  Function Name   : CalSensorData.
  Description       : 获取数据
  Input             : None.
  Output            : None.
  Return            : None.
********************************************************************/
void CalSensorData(void)
{
  memset(RawData, 0, sizeof(unsigned char) * 5);
  //1.采集温度
  WF5803_I2C_WriteCMD(WF5803IICADDR, 0X30, 0X08);
  delay_ms(10);
  //2.采集气压数据
  WF5803_I2C_WriteCMD(WF5803IICADDR, 0X30, 0X09);
  delay_ms(10);
  //2.读取气压温度数据
  WF5803_I2C_ReadNByte(WF5803IICADDR, 0X06, RawData, 5);
  //
  reading = RawData[0];
  reading = reading << 8;
  reading |= RawData[1];
  reading = reading << 8;
  reading |= RawData[2];
  // 2020-06-08 v2标定公式
  if (reading > 8388608)
  {
    fDat = (reading - 16777216) / 8388608.0f;
  }
  else
  {
    fDat = reading / 8388608.0f;
  }
  Press_Data  = 125 * (fDat - 0.1f) + 30;
  //
  reading = RawData[3];
  reading = reading << 8;
  reading |= RawData[4];
  if (reading > 32768)
  {
    Temp_Data = (reading - 65536) / 256.0f;
  }
  else
  {
    Temp_Data = reading / 256.0f;
  }
}

float GetPress(void)
{
  return Press_Data;
}

float GetTemp(void)
{
  return Temp_Data;
}
